import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/print_utils.dart';
import 'package:liuxlcommon/util/toast_util.dart';
import 'package:love_newf/app/com/base/L.dart';
import 'package:love_newf/app/com/http/Res.dart';
import 'package:love_newf/app/com/http/http_request.dart';
import 'package:love_newf/app/com/listener/room_message_listener.dart';
import 'package:love_newf/app/com/manage/txim_manage/im_manage.dart';
import 'package:love_newf/app/com/model/live_msg_type.dart';
import 'package:love_newf/app/com/model/live_result_plugin_model.dart';
import 'package:love_newf/app/com/model/room_data_model.dart';
import 'package:love_newf/app/com/model/room_info_model.dart';
import 'package:love_newf/app/com/plugin/message_plugin.dart';
import 'package:love_newf/app/com/util/my_toast.dart';
import 'package:love_newf/app/com/util/permission_utils.dart';
import 'package:love_newf/app/com/view/common_view.dart';
import 'package:love_newf/app/page/live/child/child_chat/child_chat_logic.dart';
import 'package:love_newf/app/page/live/child/gift_prop_animation/gift_prop_animation_logic.dart';
import 'package:love_newf/app/page/live/dialog/send_gift_dialog.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_callback.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_text_elem.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';

class LiveLogic extends GetxController {
  late RoomInfoModel roomInfo;
  RoomDataModel? roomData;
  late BuildContext liveContext;
  var sendGiftDialog = SendGiftDialog();
  bool showChatEdit = false;
  FocusNode chatEditFocusNode = FocusNode();

  ///显示聊天输入框
  showChatEditView() {
    showChatEdit = true;
    update();
    Future.delayed(const Duration(milliseconds: 100)).then((a) {
      FocusScope.of(liveContext).requestFocus(chatEditFocusNode);
    });
  }

  hideChatEditView() {
    showChatEdit = false;
    chatEditFocusNode.unfocus();
    update();
  }

  static LiveLogic? get logic {
    LiveLogic? logic;
    try {
      logic = Get.find<LiveLogic>(); //判断直播页面是否打开，后续添加其他判断。
    } catch (e) {
      logic = null;
    }
    return logic;
  }

  ///麦位信息
  List<RoomDataRoomMais> roomMaisList = [];

  bool isRefreshMains = true;

  get refreshMains {
    if (roomData?.roomMais == null) return;
    isRefreshMains = true;
    try {
      roomMaisList = roomData!.roomMais;
    } catch (e) {}
    update();
  }

  bool get isOwner {
    try {
      return roomInfo.userRoomVO?.userId == L.userInfo.userId;
    } catch (e) {
      return false;
    }
  }

  ///是否是主播
  bool get isAnchor {
    for (RoomDataRoomMais item in roomData?.roomMais??[]) {
      if (item.isAnchor()) {
        return true;
      }
    }
    return false;
  }

  loginRoom() async {
    // 加入群组
    V2TimCallback joinGroupRes =
        await TencentImSDKPlugin.v2TIMManager.joinGroup(
      groupID: roomInfo.id.toString() ?? "", // 需要加入群组 ID
      message: "", // 加群申请信息
      // groupType: "Public" // 群类型
    );
    if (joinGroupRes.code == 0 || joinGroupRes.code == 10013) {
      LiveResultPluginModel? info = await LiveMessagePlugin.loginRoom(roomInfo);
      if (info?.code == 0) {
        roomMaisList = roomInfo.roomMais;

        ///初始化麦位。
        isRefreshMains = true;
        update();
      }

      /// 获取 房间信息，麦位信息 最终已这个为准，上面那个可以去掉。
      getRoomData();
    } else {
      toastError("加入群聊失败 code：${joinGroupRes.code},${joinGroupRes.desc}");
    }
  }

  ///刷新房间信息
  getRoomData() async {
    RoomDataModel? data = await HttpRequest().post<RoomDataModel>(
        "/api/room/getRoomData", {"roomId": roomInfo.id},
        loadingText: "加载中...");
    if (data != null) {
      roomData = data;
      roomMaisList = roomData!.roomMais;
      //刷新麦位信息
      isRefreshMains = true;
    }
    update();
    return data;
  }

  ///邀请上麦，房主才有
  inviteShangMai(RoomDataRoomMais mais) {}

  ///申请上麦
  applyShangMai(RoomDataRoomMais mais) async {
    if (!await PermissionUtils.checkCameraPermission()) return;
    if (!await PermissionUtils.checkMicrophonePermission()) return;

    Res r = await HttpRequest().postRes("/api/room/applyShangMai",
        {"roomId": roomInfo.id, "maiIndex": mais.maiIndex},
        loadingText: "申请中...");
  }

  ///房主收到上麦申请
  receivedShangMaiApply(RoomDataInputSteamMsg inputSteamMsg) {
    if (isOwner) {
      CommonView.commDialog(
          title: inputSteamMsg.exclusive == 1 ? "申请加入专属房间" : "申请上麦，是否同意上麦请求？",
          cancelTxt: '拒绝',
          confirmTxt: '同意',
          cancel: () {
            processApply(inputSteamMsg.userId, false);
            Get.back();
          },
          confirm: () {
            processApply(inputSteamMsg.userId, true);
            Get.back();
          });
    }
  }

  void processApply(userId, bool agree) async {
    Res r = await HttpRequest().postRes("/api/room/handleMaiApply",
        {"roomId": roomInfo.id, "userId": userId, "agree": agree ? 1 : 0});
  }

  void exitRoomDialog() async {
    if (isAnchor) {
      CommonView.commDialog(
          title: "退出提示",
          message: isOwner ? "退出后将关闭直播间" : "退出后将关闭当前麦位",
          confirm: () async {
            Get.back();
            await exitRoom();
            Get.back();
          });
    } else {
      await exitRoom();
      Get.back();
    }
  }

  ///退出房间
  Future<void> exitRoom() async {
    Res r = await HttpRequest()
        .postRes("/api/room/exitRoom", {"roomId": roomInfo.id});
    if (r.isSuccess()) {
      await LiveMessagePlugin.logoutRoom();
      await TencentImSDKPlugin.v2TIMManager
          .quitGroup(groupID: roomInfo.id.toString());
    }
  }

  xiaMai(RoomDataRoomMais mais) async {
    if (isOwner) {
      Res r = await HttpRequest().postRes(
          "/api/room/kickMai", {"roomId": roomInfo.id, "userId": mais.userId},
          loadingText: "加载中...");
    } else {
      Res r = await HttpRequest().postRes(
          "/api/room/exitRoom", {"roomId": roomInfo.id, "userId": mais.userId},
          loadingText: "加载中...");
    }
  }

  ///设置自动上麦
  settingAutoShangMai(check) async {
    Res r = await HttpRequest().postRes("/api/room/roomSetting",
        {"roomId": roomInfo.id, "applyShangMai": check ? 1 : 0},
        loadingText: "设置中...");
    toast(r.msg);
    return r.isSuccess();
  }

  ///设置静音
  settingMuteMai(RoomDataRoomMais mais, bool check) async {
    Res r = await HttpRequest().postRes(
        "/api/room/roomSetting",
        {
          "roomId": roomInfo.id,
          "maiOpenSet": [
            {"maiIndex": mais.maiIndex, "open": check ? 1 : 0}
          ]
        },
        loadingText: "设置中...");
    toast(r.msg);
    return r.isSuccess();
  }

  kicked() {
    //未完成
  }

  sendTextMessage(String content) {
    if (content.trim().isEmpty) {
      toastError("聊天信息不能为空！");
      return;
    }
    ImManage()
        .sendMessage(content.trim(), groupID: roomInfo.id.toString())
        .then((item) {
      if (item != null) receiveMessage(item);
    });
    hideChatEditView();
  }

  ///直播间 消息。
  receiveMessage(V2TimMessage message) {
    Get.find<ChildChatLogic>().receiveMessage(message);
  }

  ///收到礼物信息。
  receiveGiftMessage(RoomDataModel roomData) {
    //1. 发送聊天信息
    var message = V2TimMessage(elemType: LiveMsgType.GIFT);
    message.textElem = V2TimTextElem(text: json.encode(roomData.toJson()));
    receiveMessage(message);
    //2.播放
    playGift(roomData.givePropMsg!);
  }

  playGift(RoomDataGivePropMsg prop) {
    try {
      Get.find<GiftPropAnimationLogic>().play(prop);
    } catch (e) {
      toastError("礼物组件未创建");
    }
  }
}
